package com.summer.service.impl.thirdpart;

import com.summer.entity.DictionaryCache;
import com.summer.entity.UserHulu;
import com.summer.mapper.UserHuluDAO;
import com.summer.service.thirdpart.IHuLuService;
import com.summer.util.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * 类描述：芝麻信用相关接口 <br>
 * 每次发出请求之前插入订单信息，返回后更新订单信息<br>
 * 此类不做任何业务处理，仅拼接参数请求第三方，必须使用trycath，并且不向上抛出异常以保证插入或更新的订单不会回滚<br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午03:41:28 <br>
 * 
 * @version
 * 
 */
@Slf4j
@Service
public class HuLuService implements IHuLuService {
    @Resource
    private UserHuluDAO userHuluDAO;

    /**
     * 获取数据令牌
     * @return
     */
    public String accessToken(String userId){
        log.info("（HL数据）进入获取数据令牌方法。。。");
        String accessToken = ""; //数据令牌
        String result = "";  //响应信息
        //请求地址
        Map<String, String> keys = DictionaryCache.translateMap.get(BackConfigParams.HL);
        String url = keys.get("hl_access_token");
        log.info("请求地址："+url);
        //传入参数
        String companyAccount = keys.get("hl_lyb_company_code");
        String signature=keys.get("hl_signature");  //公司签名
        try {
            companyAccount = URLEncoder.encode(companyAccount,"UTF-8");
            signature = URLEncoder.encode(signature, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //组装一下。
        HashMap<String, Object>  params = new HashMap<String, Object>();
        params.put("companyAccount", companyAccount);
        params.put("signature", signature);
        //请求方式
        String method="GET";
        log.info("请求方式："+method);
        //拼接请求信息
        HashMap<String, Object> httpsInfo = new HashMap<String, Object>();
        httpsInfo.put("url",url );
        httpsInfo.put("params",params);
        httpsInfo.put("method",method );
        httpsInfo.put("times","默认180000毫秒");
        //处理url请求参数
        String strUrl= url.replace("{companyAccount}", companyAccount);
        strUrl= strUrl.replace("{signature}", signature);
        //开始请求
        try {
            log.info("开始请求获取数据令牌...");
            result=CommCallInterface.getInstance().commHttp(strUrl, null, method);
//			log.info("请求返回信息："+result);
            log.info("获取数据令牌结束。");
        } catch (Exception e) {
            log.error("获取数据令牌接口异常:",httpsInfo.toString(),e);
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        if(jsonObject.get("code").toString().equals("0")){
            JSONObject object = jsonObject.getJSONObject("data");
            accessToken = object.getString("access_token");//数据令牌
        }
        return accessToken;
    }


    /**
     * 查询报告
     */
    @Override
    public ServiceResult findUserReport(HashMap<String, Object> params) {
        ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
        String result = "";
        String accessToken = ""; //数据令牌
        try {
            Object userId = params.get("userId");
            if(userId!=null&&!userId.equals("")){
                accessToken = accessToken(userId.toString()); //获取数据令牌
            }
            Object token = params.get("token");
            if (token != null && userId != null && !accessToken.equals("")) {
                Map<String, String> keys = DictionaryCache.translateMap.get(BackConfigParams.HL);
                String companyAccount =keys.get("hl_lyb_company_code");
                String url = keys.get("hl_report");
                //参数
                HashMap<String, Object> paramsInfo = new HashMap<String, Object>();
                paramsInfo.put("accessToken",accessToken);
                paramsInfo.put("token",token);
                paramsInfo.put("companyAccount",companyAccount);
                //拼接
                HashMap<String, Object> httpsInfo = new HashMap<String, Object>();
                httpsInfo.put("url",url );
                httpsInfo.put("params",paramsInfo);
                httpsInfo.put("method","GET" );
                httpsInfo.put("times","默认180000毫秒");
                //处理url
                String strUrl = url.replace("{collectToken}", token.toString());
                strUrl = strUrl.replace("{companyAccount}",companyAccount );
                strUrl = strUrl.replace("{accessToken}",accessToken );
                try {
                    log.info("开始请求获取葫芦数据的原始报告...");
                    result=CommCallInterface.getInstance().commHttp(strUrl, null, "GET");
//			    	log.info("请求返回信息："+result);
                    log.info("（葫芦数据）获取原始报告结束。");
                } catch (Exception e) {
                    serviceResult = new ServiceResult("100", "请求接口异常");
                    log.error("（葫芦数据）获取原始报告请求接口异常:",httpsInfo.toString(),e);
                }
                try {
                    //开始解析
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    if (jsonObject.get("code").toString().equals("16642")) {
                        serviceResult = new ServiceResult("200", result);
                    } else {
                        serviceResult = new ServiceResult("300", "查询报告失败");
                    }
                } catch (Exception e) {
                    log.error("getHZ findUserReport error ", e);
                    serviceResult = new ServiceResult("300", "解析数据出错");
                }
            } else {
                serviceResult = new ServiceResult("400", "必要参数不足！");
            }
        } catch (Exception e) {
            log.error("葫芦数据查看报告方法信息异常：,params=" + params, e);
        }
        return serviceResult;
    }


    /**
     * 组装葫芦数据
     * @param params
     * @return
     */
    public UserHulu createhl(HashMap<String, Object> params) {
        UserHulu hulu = null;
        Object userId = params.get("userId");
        try {
            Object detail = params.get("detail");
            Object firstContactPhone = params.get("firstContactPhone");
            Object secondContactPhone = params.get("secondContactPhone");
            if (userId != null && detail != null && firstContactPhone != null && secondContactPhone != null) {
                int jxlZjDkNum = 0;
                int jxlBjDkNum = 0;
                BigDecimal yjHf = BigDecimal.ZERO;
                int yjHfHelp = 0;
                int jxlAmthNum = 0;
                int jxlHtPhoneNum = 0;
                int jxlGjTs = 0;
                int link1Num = 0;
                int link2Num = 0;
                int jxlLink2Days = 0;
                int jxlLink1Days = 0;
                int jxlLink2Order = 0;
                int jxlLink1Order = 0;
                int jxlPhoneRegDays = -1;
                Date lastHf = null;
                int jxlTotal = 0;
                int jxlLxGjTs = 0;
                byte jxlRealName = 2;// 运营商是否已实名
                int goAmNum = 0;// 去澳门次数
                int zjlxrBlack = 0;// 直接联系人黑名单个数  --- 葫芦数据没有该值信息
                int jjlxrBlack = 0;// 间接联系人黑名单个数 --  葫芦数据没有该值信息
                int yqjjBlack = 0;// 引起间接黑名单个数  -- 葫芦数据没有该值信息
                byte jxlSamePhoneCard = 1;// 聚信立手机号和身份证号是否匹配，默认是1匹配
                JSONObject jsonObject = JSONObject.fromObject(detail);
                if (jsonObject.containsKey("data")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date now = sdf.parse(sdf.format(new Date()));
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    if (jsonObject2.containsKey("behavior_check")) {
                        JSONArray jsonArray = jsonObject2.getJSONArray("behavior_check");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                                String checkPoint = jsonObject3.getString("check_point");
                                String evidence = jsonObject3.getString("evidence");
                                if ("贷款类号码联系情况".equals(checkPoint)) {                      //jxlZjDkNum  jxlBjDkNum   聚信立贷款类型主叫个数和被叫个数
                                    String flag = "次共";
                                    String flag2 = "主叫";
                                    String flag3 = "被叫";
                                    String flag4 = "联系列表";
                                    if (evidence.indexOf(flag4) >= 0) {
                                        String[] tmp = evidence.split(";");
                                        if (tmp != null && tmp.length > 0) {
                                            for (String detail2 : tmp) {
                                                while (detail2.indexOf(flag2) >= 0) {
                                                    int index2 = detail2.indexOf(flag2);
                                                    int index1 = detail2.indexOf(flag);
                                                    jxlZjDkNum += Integer.valueOf(detail2.substring(index2 + flag2.length(), index1));
                                                    detail2 = detail2.substring(index1 + 1);
                                                    int index3 = detail2.indexOf(flag3);
                                                    int index4 = detail2.indexOf(flag);
                                                    jxlBjDkNum += Integer.valueOf(detail2.substring(index3 + flag3.length(), index4));
                                                    detail2 = detail2.substring(index4 + 1);
                                                }
                                            }
                                        }
                                    }
                                } else if ("澳门电话通话情况".equals(checkPoint)) {   // jxlAmthNum  聚信立澳门通话次数统计
                                    String flag = "澳门地区号码通话";
                                    String flag2 = "次";
                                    int index = evidence.indexOf(flag);
                                    if (index >= 0) {
                                        int index2 = evidence.indexOf(flag2);
                                        jxlAmthNum += Integer.valueOf(evidence.substring(index + flag.length(), index2));
                                    }
                                } else if ("互通过电话的号码数量".equals(checkPoint)) { //jxlHtPhoneNum  聚信立互通电话数量统计
                                    String flag = "互通过电话的号码有";
                                    String flag2 = "个";
                                    int index = evidence.indexOf(flag);
                                    if (index >= 0) {
                                        int index2 = evidence.indexOf(flag2);
                                        jxlHtPhoneNum += Integer.valueOf(evidence.substring(index + flag.length(), index2));
                                    }

                                } else if ("关机情况".equals(checkPoint)) {
                                    String flag0 = "天内关机";
                                    if (evidence.indexOf(flag0) >= 0) {
                                        String[] array = evidence.split(flag0);
                                        if (array != null && array.length > 0) {
                                            String flag = "天";
                                            for (int j = 0; j < array.length; j++) {   // jxlTotal  聚信立统计关机天数
                                                String tmp = array[j];
                                                if (j == 0) {
                                                    jxlTotal += Integer.valueOf(tmp.substring(10));
                                                } else {                                 // jxlGjTs  聚信立关机天数
                                                    int index = tmp.indexOf(flag);
                                                    if (index >= 0) {
                                                        jxlGjTs += Integer.valueOf(tmp.substring(0, index));
                                                    }
                                                }
                                            }
                                            String flag2 = "次: ";
                                            int index2 = evidence.indexOf(flag2);
                                            if (index2 >= 0) {
                                                evidence = evidence.substring(index2 + flag2.length());
                                                String[] array2 = evidence.split("/");
                                                for (int j = 0; j < array2.length; j++) {   //jxlLxGjTs  聚信立最大关机天数
                                                    String tmp = array2[j];
                                                    String flag3 = ", ";
                                                    String flag4 = "天";
                                                    int gj = 0;
                                                    int index3 = tmp.indexOf(flag3);
                                                    int index4 = tmp.indexOf(flag4);
                                                    if (index3 >= 0 && index4 >= 0) {
                                                        gj = Integer.valueOf(tmp.substring(flag3.length() + index3, index4));
                                                        if (gj > jxlLxGjTs) {
                                                            jxlLxGjTs = gj;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                    if (jsonObject2.containsKey("cell_behavior")) {
                        JSONArray jsonArray = jsonObject2.getJSONArray("cell_behavior");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                                JSONArray jsonArray2 = jsonObject3.getJSONArray("behavior");
                                for (int j = 0; j < jsonArray2.size(); j++) {
                                    JSONObject jsonObject4 = jsonArray2.getJSONObject(j);
                                    String amount = jsonObject4.getString("total_amount");
                                    if (!"-1".equals(amount)&&!"-1.0".equals(amount)) {
                                        yjHfHelp += 1;
                                        yjHf = yjHf.add(new BigDecimal(amount));
                                    }
                                }
                            }
                        }
                    }
                    if (jsonObject2.containsKey("collection_contact")) {
                        JSONArray jsonArray = jsonObject2.getJSONArray("collection_contact");
                        if (jsonArray != null && jsonArray.size() > 0) {
//							Map<String, Float> callLenMap = new HashMap<String, Float>(); //每个联系人的通话时长
                            for (int i = 0; i < jsonArray.size(); i++) {                          //第一联系人通话册书 ， 第二联系人通话次数   ， 与第一（二）联系人最晚联系时间到目前有多少天
                                JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                                JSONArray jsonArray2 = jsonObject3.getJSONArray("contact_details");
                                //call_len  phone_num
                                if (jsonArray2 != null && jsonArray2.size() > 0) {
                                    for (int j = 0; j < jsonArray2.size(); j++) {
                                        JSONObject jsonObject4 = jsonArray2.getJSONObject(j);
                                        int num = jsonObject4.getInt("call_cnt");
                                        String phone = jsonObject4.getString("phone_num");
                                        String transEnd = jsonObject4.getString("trans_end");
//										Object callLen = jsonObject4.get("call_len");
                                        int num2 = 0;
                                        if (!"".equals(transEnd) && !"null".equals(transEnd)) {
                                            Date end = sdf.parse(transEnd.substring(0, 10));
                                            num2 = DateUtil.daysBetween(end, now);
                                        }
                                        if (firstContactPhone.equals(phone)) {
                                            link1Num += num;
                                            jxlLink1Days += num2;
                                        } else if (secondContactPhone.equals(phone)) {
                                            link2Num += num;
                                            jxlLink2Days += num2;
                                        }
                                        //存储联系人以及通话时长
//										if(callLen!=null){
//											callLenMap.put(phone, Float.parseFloat(callLen.toString()));
//										}
                                    }
                                }
                            }
                            //  把存储联系人信息的map集合进行排序
//							ValueComparatorUtil bvc =  new ValueComparatorUtil(callLenMap);
//							TreeMap<String,Float> sorted_map = new TreeMap<String,Float>(bvc);
//							sorted_map.putAll(callLenMap);
//							Iterator it = sorted_map.keySet().iterator();
//							int count = 0 ; // 来记录排名
//							while (it.hasNext()) {
//								count++;
//								String key = it.next().toString();
//								if(firstContactPhone.equals(key)){  //第一联系人
//									jxlLink1Order=count;
//								}else if (secondContactPhone.equals(key)){  //第二联系人
//									jxlLink2Order=count;
//								}
//
//							}
                        }
                    }


                    //第一，第二联系人通话时长排名
                    if(jsonObject2.containsKey("contact_list")){
                        JSONArray jsonArray = jsonObject2.getJSONArray("contact_list");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            Map<String, Float> callLenMap = new HashMap<String, Float>(); //每个联系人的通话时长
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                                Object callLen  =  jsonObject3.get("call_len");   //取电话
                                String phone = jsonObject3.getString("phone_num");   //取时长
                                //存储联系人以及通话时长
                                if(callLen!=null){
                                    callLenMap.put(phone, Float.parseFloat(callLen.toString()));
                                }
                            }
                            //  把存储联系人信息的map集合进行排序
                            ValueComparatorUtil bvc =  new ValueComparatorUtil(callLenMap);
                            TreeMap<String,Float> sorted_map = new TreeMap<String,Float>(bvc);
                            sorted_map.putAll(callLenMap);
                            Iterator it = sorted_map.keySet().iterator();
                            int count = 0 ; // 来记录排名
                            while (it.hasNext()) {
                                count++;
                                String key = it.next().toString();
                                if(firstContactPhone.equals(key)){  //第一联系人
                                    jxlLink1Order=count;
                                }else if (secondContactPhone.equals(key)){  //第二联系人
                                    jxlLink2Order=count;
                                }
                            }
                        }

                    }



                    if (jsonObject2.containsKey("application_check")) {
                        JSONArray jsonArray = jsonObject2.getJSONArray("application_check");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                            Object check_point = jsonObject3.get("check_point");
                            Object evidence = jsonObject3.get("evidence");
                            // 姓名身份证号码任何一个匹配则是匹配，任何一个不匹配则是不匹配，其他情况是运营商未提供
                            if((check_point!=null&&check_point.toString().equals("身份证号码是否与运营商数据匹配")) || (check_point!=null&&check_point.toString().equals("姓名是否与运营商数据匹配"))){
                                if(evidence!=null){
                                    if(evidence.toString().indexOf("匹配成功")>=0){
                                        jxlSamePhoneCard = 1;
                                        break;
                                    }else if(evidence.toString().indexOf("匹配失败")>=0){
                                        jxlSamePhoneCard = 2;
                                        break;
                                    }else{
                                        jxlSamePhoneCard = 3;
                                    }
                                }
                            }
                        }
                    }
                    if (jsonObject2.containsKey("trip_info")) {  // goAmNum  去澳门次数统计
                        JSONArray jsonArray = jsonObject2.getJSONArray("trip_info");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObject3 = jsonArray.getJSONObject(i);
                                if ("澳门".equals(jsonObject3.getString("trip_dest"))) {
                                    goAmNum += 1;
                                }
                            }
                        }
                    }
                    if(jsonObject2.containsKey("data_source")){   // jxlRealName  实名认证获取
                        JSONArray jsonArray = jsonObject2.getJSONArray("data_source");
                        if(jsonArray!=null && jsonArray.size()>0){
                            JSONObject jsonObject3 = jsonArray.getJSONObject(0);
                            if(jsonObject3.containsKey("reliability")){
                                if(jsonObject3.get("reliability").equals("实名认证")){
                                    jxlRealName = 1 ;
                                }
                            }
                            if(jsonObject3.containsKey("binding_time")){  // //jxlPhoneRegDays   聚信立手机开户时间距离当前的天数
                                String bingdingTime = jsonObject3.getString("binding_time");    //入网时间或开户时间
                                if (StringUtils.isNotBlank(bingdingTime)) {
                                    Date end = sdf.parse(bingdingTime.substring(0, 10));
                                    jxlPhoneRegDays = DateUtil.daysBetween(end, now);
                                }
                            }
                        }

                    }
                }
                if (yjHfHelp != 0) {   //yjHf  聚信立月均话费
                    yjHf = yjHf.divide(new BigDecimal(yjHfHelp), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 如果没有获取到入网时间
                if (jxlPhoneRegDays == -1) {   //jxlPhoneRegDays   聚信立手机开户时间距离当前的天数
                    // 没有账单，则入网时间为0
                    jxlPhoneRegDays = 0;
                }
                BigDecimal jxlGjBl = BigDecimal.ZERO;
                if (jxlTotal != 0) { // jxlGjBl  聚信立关机天数比例统计
                    jxlGjBl = new BigDecimal(jxlGjTs).divide(new BigDecimal(jxlTotal), 2, BigDecimal.ROUND_UP);
                }
                Date now = new Date();
                hulu = new UserHulu(Integer.parseInt(userId.toString()),jxlZjDkNum, jxlBjDkNum, yjHf, jxlLink2Days, jxlLink1Days,
                        link2Num,
                        link1Num, jxlLink2Order, jxlLink1Order, jxlGjTs, jxlHtPhoneNum, jxlAmthNum, jxlPhoneRegDays, detail + "", jxlTotal, jxlGjBl,
                        jxlLxGjTs, jxlRealName, goAmNum, zjlxrBlack, jjlxrBlack, yqjjBlack, jxlSamePhoneCard,now);
            }
        } catch (Exception e) {
            log.error("createJxl error userId=" + userId, e);
        }
        return hulu;
    }

    /**
     * 获取token
     */
    @Override
    public ServiceResult getToken(HashMap<String, Object> params) {
        ServiceResult serviceResult = new ServiceResult("500","未知异常，请稍后重试！");
        String result = "";//请求HL返回数据
        JSONObject json = new JSONObject();
        Object name = params.get("userName");
        Object identity_card_number =  params.get("cardNum");
        Object cell_phone_number =  params.get("userPhone");
        Object userId = params.get("userId");
        try {
            if(name!=null&&identity_card_number!=null&&cell_phone_number!=null&&userId!=null){
                Map<String, String> keys = DictionaryCache.translateMap.get(BackConfigParams.HL);
                //获取请求地址
                String url = keys.get("hl_rz_url");
                String company_account = keys.get("hl_lyb_company_code")  ;
                //组合请求参数
                HashMap<String, Object>  requestParams = new HashMap<String, Object>();
                requestParams.put("name",name.toString() );
                requestParams.put("identity_card_number", identity_card_number);
                requestParams.put("cell_phone_number",cell_phone_number );
                requestParams.put("company_account",company_account ); // 机构账号
                requestParams.put("first_contact_name",params.get("first_contact_name").toString() );
                requestParams.put("first_contact_type",params.get("first_contact_type").toString());
                requestParams.put("first_contact_cell_phone_number", params.get("first_contact_cell_phone_number").toString());
                requestParams.put("second_contact_name",params.get("second_contact_name").toString());
                requestParams.put("second_contact_type",params.get("second_contact_type").toString());
                requestParams.put("second_contact_cell_phone_number",params.get("second_contact_cell_phone_number").toString());
                log.info("    ------请求参数："+requestParams.toString());
                //提交方式
                String method="POST";
                //设置请求时间
                HashMap<String, Object> times = new HashMap<String, Object>();
                times.put("soketOut", 180000);
                times.put("connOut", 180000);
                //拼接请求信息
                HashMap<String, Object> httpsInfo = new HashMap<String, Object>();
                httpsInfo.put("url",url );
                httpsInfo.put("params",requestParams.toString());
                httpsInfo.put("method",method );
                httpsInfo.put("times",times.toString() );
                //开始请求
                try {
                    log.info("    ------开始请求运营商认证...");
                    result = WebClient.getInstance().postJsonData(url, JSONObject.fromObject(requestParams).toString(), times);
                    log.info("    ------运营商请求结束。");
                } catch (Exception e) {
                    serviceResult = new ServiceResult("100", "请求接口异常");
                    log.error("HL运行商认证方法---请求接口异常:",httpsInfo.toString(),e);
                }
                //开始解析
                try {
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    if ("8209".equals(jsonObject.getString("code"))) {   //8209 请求成功
                        log.info("    ------响应结果正常！");
                        jsonObject = jsonObject.getJSONObject("data");
                        //采集的网站名称     例：上海电信, ...
                        //认证令牌（该令牌十分钟有效）
                        //更新响应信息
                        serviceResult = new ServiceResult(ServiceResult.SUCCESS, jsonObject.getString("token"), jsonObject.getString("collect_website"));
                    }else{
                        serviceResult = new ServiceResult(jsonObject.getString("code"), jsonObject.getString("message"));
                    }
                } catch (Exception e) {
                    serviceResult = new ServiceResult("300", "解析数据出错");
                    log.error("HL运行商认证方法---解析返回信息异常：",e);
                }
            }else{
                serviceResult = new ServiceResult("400", "必要参数不足！");
            }
        } catch (Exception e) {
            log.error("HL运行商认证方法---信息异常：" + params.toString(), e);
        }finally{
            log.info(" HL ------结束运营商认证方法！");
        }
        return serviceResult;
    }


    /**
     * 获取手机验证码
     */
    @Override
    public ServiceResult getCaptcha(HashMap<String, Object> params) {
        log.info(" HL ------进入postCaptcha方法...");
        log.info("    ------产品传入参数：dataJso---"+params.toString());
        ServiceResult serviceResult = new ServiceResult("500","未知异常，请稍后重试！");
        String info =""; //标识记录  提交登陆密码、登录(或查询详单)短信验证码接口、提交查询密码
        String result = "";//请求HL返回数据
        String act="";//记录标识
        JSONObject json = new JSONObject();
        Object token =  params.get("token");
        Object password =  params.get("password"); //登录密码
        Object queryPwd = params.get("queryPwd"); //查询密码
        Object userId = params.get("userId");
        Object userPhone = params.get("userPhone");
        Object website = params.get("website");//手机归属地信息    --例：上海移动
        Object CAPTCHA = params.get("CAPTCHA");//提交验证码
        try {
            if(token!=null&&userId!=null){
                //获取请求地址
                Map<String, String> keys = DictionaryCache.translateMap.get(BackConfigParams.HL);
                String url =keys.get("hl_collect_url");
                //组合请求参数
                HashMap<String, Object>  requestParams = new HashMap<String, Object>();
                requestParams.put("token",token );
                if (queryPwd != null && StringUtils.isNotBlank(queryPwd.toString())) {   //提交查询密码
                    info="提交查询密码";
                    requestParams.put("query_password",queryPwd);
                    act=Constant.SUB_QUERY_PASSWORD;
                }else if(CAPTCHA != null && StringUtils.isNotBlank(CAPTCHA.toString())){  //提交登录(或查询详单)短信验证码接口
                    info="登录(或查询详单)短信验证码";
                    requestParams.put("captcha",CAPTCHA );
                    act=Constant.SUB_CAPTCHA;
                }else if(password != null && StringUtils.isNotBlank(password.toString())){ //登陆密码
                    info="提交登陆密码";
                    requestParams.put("password",password );
                    act=Constant.SUB_PASSWORD;
                }
                requestParams.put("password",password );
                log.info("    ------请求参数："+requestParams.toString());
                //提交方式
                String method="POST";
                log.info("    ------请求方式："+method);
                //设置请求时间
                HashMap<String, Object> times = new HashMap<String, Object>();
                times.put("soketOut", 180000);
                times.put("connOut", 180000);
                log.info("    ------请求时间："+times.toString());
                //拼接请求信息
                HashMap<String, Object> httpsInfo = new HashMap<String, Object>();
                httpsInfo.put("url",url );
                httpsInfo.put("params",requestParams.toString());
                httpsInfo.put("method",method );
                httpsInfo.put("times",times.toString() );
                //开始请求
                try {
                    log.info("    ------开始请求"+info+"...");
                    result = WebClient.getInstance().postJsonData(url,JSONObject.fromObject(requestParams).toString(), times);
//					log.info("    ------请求返回信息："+result);
                    log.info("    ------"+info+"结束。");
                } catch (Exception e) {
                    serviceResult = new ServiceResult("100", "请求接口异常");
                    log.error("HL提交"+info+"---请求接口异常:",httpsInfo.toString(),e);
                }
                //开始解析
                try {
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    if("12291".equals(jsonObject.getString("code"))){  //数据源授权成功    认证流程结束的流程码  （ 联通只需要提供服务密码）
                        log.info("    ------响应结果正常,服务密码授权成功！");
                        serviceResult = new ServiceResult("100", "开始采集数据!");
                        //提取
                        if (token != null) {
                            saveToken(token.toString(), Integer.valueOf(userId.toString()),userPhone.toString());
                        }
                    }else if("13824".equals(jsonObject.getString("code"))){  //北京移动会出现输入查询密码或短信验证码
                        log.info(" HL ------提交查询密码（北京移动会出现这样的情况..）...");
                        //TODO  北京移动
                        if(queryPwd!=null&&token!=null&&website!=null){
                            serviceResult = getChinamobilebj( website.toString(), token.toString(), queryPwd.toString(), url, times, userId.toString(),userPhone.toString() );
                        }
                    }else if("12800".equals(jsonObject.getString("code"))) {   //需要重新发送验证码的信息
                        log.info("    ------响应结果正常，开始发送验证码！");
                        log.info("    ------响应信息：code="+jsonObject.getString("code")+" , message="+jsonObject.getString("message"));
                        //打印响应data值
//						log.info("    ------data："+jsonObject.getJSONObject("data"));
                        //更新响应信息
                        serviceResult = new ServiceResult("200", "短信已发送至您手机，请耐心等待并尽快输入验证码完成验证");
                    }else{   //
                        log.info("    ------code!=12291(响应结果正常，不需要验证码，一步认证)||code!=12800(响应结果正常，需要数据验证码||code!=13824(响应结果正常，判断是否是北京移动，若是修改参数，继续提交！))");
                        serviceResult = new ServiceResult(jsonObject.getString("code"), jsonObject.getString("message"));
                    }
                } catch (Exception e) {
                    serviceResult = new ServiceResult("300", "解析数据出错");
                    log.error("HL"+info+"---解析返回信息异常：",e);
                }
            }else{
                serviceResult = new ServiceResult("400", "必要参数不足！");
            }
        } catch (Exception e) {
            log.error("HL"+info+"方法---信息异常：" + params.toString(), e);
        }finally{
            log.info(" HL ------结束"+info+"方法！");
        }
        return serviceResult;
    }

    private void saveToken(String token, Integer userId,String userPhone) {

        UserHulu old = userHuluDAO.selectByUserId(userId);
        if(null==old){
            UserHulu userHulu = new UserHulu();
            userHulu.setUserId(userId);
            userHulu.setPhone(userPhone);
            userHulu.setJxlTokenTime(new Date());
            userHulu.setStatus(Constant.USER_AUTHENTIC);
            userHulu.setJxlToken(token);  //实则是HL token
            userHuluDAO.insertSelective(userHulu);// 认证成功，修改用户状态
        }
    }


    /**
     * 查询手机号码归属地，判断模板
     */
    @Override
    public CallBackResult findMobileBelong(HashMap<String, Object> params) {
        CallBackResult rest = new CallBackResult(CallBackResult.BUSINESS_ERROR, "获取手机运营商异常");
        Object phone = params.get("phone");
        Object website = params.get("website");
        Object IdNumber = params.get("idNumber");
        String operator="";
        String operatorType="";
        String sendPhone="";
        String province="";
        if(StringUtils.isNotEmpty(website.toString())){
            if(website.toString().contains("联通")){
                operator="联通";
                sendPhone="10010";
                operatorType="2";
            }else if(website.toString().contains("移动")){
                operator="移动";
                sendPhone="10086";
                operatorType="1";
            }else if(website.toString().contains("电信")){
                operator="电信";
                sendPhone="10001";
                operatorType="3";
            }else{
                return rest;
            }
        }
        province=website.toString().replace(operator,"");
        String sendMsg = "";
        if(operatorType.equals("2")){
            String msgs = sendMsg.substring(0, sendMsg.lastIndexOf("#")+1);
            String idNumber = IdNumber.toString().substring(IdNumber.toString().length()-6);
            sendMsg = msgs + idNumber;
        }
        JSONObject data = new JSONObject();
        data.put("sendMsg", sendMsg);
        data.put("sendPhone", sendPhone);
        data.put("province", province);
        data.put("jxlName", operator);
        data.put("phone", phone);
        data.put("jxlType", operatorType);
        rest.setData(data);
        rest.setCode(CallBackResult.SUCCESS);
        rest.setMessage("获取手机运行商成功");
        return rest;
    }



    /**
     * 北京移动
     * @return
     */
    public ServiceResult getChinamobilebj(String website,String token,String queryPwd,String url,HashMap<String,
            Object> times,String userId,String userPhone ){
        ServiceResult serviceResult = new ServiceResult("500","未知异常，请稍后重试！");
        String result="";
        if("北京移动".equals(website)){
            //参数
            HashMap<String, Object> queryPwdParams = new HashMap<String, Object>();
            queryPwdParams.put("token",token );
            queryPwdParams.put("query_password",queryPwd );
            //拼接请求信息
            HashMap<String, Object> httpsInfo2 = new HashMap<String, Object>();
            httpsInfo2.put("url",url );
            httpsInfo2.put("params",queryPwdParams.toString());
            httpsInfo2.put("method","POST" );
            httpsInfo2.put("times",times.toString() );
            //请求
            result = WebClient.getInstance().postJsonData(url, queryPwdParams.toString(), times);
            JSONObject resultJson = JSONObject.fromObject(result);
            //开始解析
            if("12291".equals(resultJson.getString("code"))){  //数据源授权成功    认证流程结束的流程码   联通只需要提供服务密码
                log.info("    ------响应结果正常。");
                serviceResult = new ServiceResult("100", "开始采集数据!");
                //提取
                if (token != null) {
                    saveToken(token, Integer.valueOf(userId),userPhone);
                }
            }else{
                log.info("    ------响应结果异常，采集失败！");
                log.info("    ------异常信息："+resultJson.getString("code"), resultJson.getString("message"));
                serviceResult = new ServiceResult(resultJson.getString("code"), resultJson.getString("message"));
            }
        }
        return serviceResult;
    }

}